/*
 * BSplineEditor.java
 *
 * Created on den 2 november 2008, 03:02
 */
package bezier;

import bezier.curves.BSplineCurve;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author  Gussoh
 */
public class BSplineEditorDialog extends javax.swing.JDialog {

    private BezierPanel bp;
    private BSplineCurve curve,  backupCurve;
    private int desiredDegree;
    private List<Double> desiredKnots = new ArrayList<Double>();

    /** Creates new form BSplineEditor */
    public BSplineEditorDialog(BezierPanel bp, BSplineCurve curve) {
        this.bp = bp;
        this.curve = curve;
        backupCurve = new BSplineCurve(curve.getControlPoints(), curve.getKnots(), curve.getDegree());
        initComponents();

        degreeTextField.setText(curve.getDegree() + "");
        StringBuilder sb = new StringBuilder();
        for (Double knot : curve.getKnots()) {
            sb.append(knot).append(", ");
        }
        knotsTextField.setText(sb.toString());

        desiredDegree = curve.getDegree();
        desiredKnots = curve.getKnots();

        setLocationRelativeTo(bp);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        degreeTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        knotsTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        undoButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(bezier.BezierApp.class).getContext().getResourceMap(BSplineEditorDialog.class);
        degreeTextField.setText(resourceMap.getString("degreeTextField.text")); // NOI18N
        degreeTextField.setName("degreeTextField"); // NOI18N
        degreeTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                degreeTextFieldKeyReleased(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        knotsTextField.setText(resourceMap.getString("knotsTextField.text")); // NOI18N
        knotsTextField.setName("knotsTextField"); // NOI18N
        knotsTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                knotsTextFieldKeyReleased(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        undoButton.setText(resourceMap.getString("undoButton.text")); // NOI18N
        undoButton.setName("undoButton"); // NOI18N
        undoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                undoButtonActionPerformed(evt);
            }
        });

        closeButton.setText(resourceMap.getString("closeButton.text")); // NOI18N
        closeButton.setName("closeButton"); // NOI18N
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        errorLabel.setText(resourceMap.getString("errorLabel.text")); // NOI18N
        errorLabel.setName("errorLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(degreeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(knotsTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(closeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(undoButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(degreeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(knotsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(undoButton)
                        .addComponent(closeButton))
                    .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
    dispose();
}//GEN-LAST:event_closeButtonActionPerformed

private void undoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoButtonActionPerformed
    curve.setControlPoints(backupCurve.getControlPoints());
    curve.setDegree(backupCurve.getDegree());
    curve.setKnots(backupCurve.getKnots());
    dispose();
    bp.stateChanged();
}//GEN-LAST:event_undoButtonActionPerformed

private void degreeTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_degreeTextFieldKeyReleased
    try {
        desiredDegree = Integer.parseInt(degreeTextField.getText());
        if (curve.getControlPoints().size() > desiredDegree && desiredDegree > 0) {
            validateCurve();
        } else {
            errorLabel.setText("Degree must be less than " + curve.getControlPoints().size());
        }
    } catch (NumberFormatException ex) {
        errorLabel.setText("Degree is not a number");
    }
}//GEN-LAST:event_degreeTextFieldKeyReleased

private void knotsTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_knotsTextFieldKeyReleased
    String[] knotsString = knotsTextField.getText().split(",");
    List<Double> tempKnots = new ArrayList<Double>();
    try {
        for (String knot : knotsString) {
            if (knot != null && knot.trim().length() > 0) {
                tempKnots.add(Double.parseDouble(knot.trim()));
            }
        }
        desiredKnots.clear();
        desiredKnots.addAll(tempKnots);
        validateCurve();
    } catch (NumberFormatException ex) {
        errorLabel.setText("Could not parse knot: " + ex.getMessage());
    }
}//GEN-LAST:event_knotsTextFieldKeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JTextField degreeTextField;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField knotsTextField;
    private javax.swing.JButton undoButton;
    // End of variables declaration//GEN-END:variables

    private void validateCurve() {
        StringBuilder sb = new StringBuilder("<html>");
        boolean valid = true;
        for (int i = 0; i < desiredKnots.size() - 1; i++) {
            if (desiredKnots.get(i) > desiredKnots.get(i + 1)) {
                sb.append("Knot sequence is not in ascending order.").append("<br>");
                valid = false;
                break;
            }
        }
        if (desiredDegree + 1 + curve.getControlPoints().size() != desiredKnots.size()) {
            sb.append("Number of knots: " + desiredKnots.size() + ", should be: " + (desiredDegree + 1 + curve.getControlPoints().size())).append("<br>");
            sb.append("or change degree to: " + (desiredKnots.size() - curve.getControlPoints().size() - 1));
        } else if(valid) {
            curve.setDegree(desiredDegree);
            curve.setKnots(desiredKnots);
            bp.stateChanged();
        }
        sb.append("</html>");
        errorLabel.setText(sb.toString());
    }
}
